package com.ruoyi.ggsearch.utils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.core.utils.http.SimpleHttpClientUtil;
import com.ruoyi.ggsearch.domain.GgDomain;
import com.ruoyi.ggsearch.domain.GgKeyWords;
import com.ruoyi.ggsearch.domain.GgSearchResult;
import org.apache.http.Consts;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;


public class ApiSearchTool {

    private static String host = "https://customsearch.googleapis.com";
    private static String path = "/customsearch/v1";

    //yangjin012345@gmail.com
    //private static String key="AIzaSyBZMgqDR-4rQCIY8wReuYIbyddzUh6kTDQ";
    //private static String cx="158cd33fde92146d9";

    //beautifulhouw@gmail.com
    private static String key="AIzaSyBvmWAlnldcWBbpb1sDQ91BtycdZEKTASs";
    private static String cx="f0e1e719dc9a049e4";

    public static HttpResponse customsearch(String q, Integer start, Integer num) throws IOException {
        Map<String, String> map  = new HashMap<>();
        map.put("key",key);
        map.put("cx",cx);
        map.put("q",q);
        map.put("num",num.toString());//每页数量1-10
        map.put("start",start.toString());//第一条记录索引
        HttpResponse httpResponse = SimpleHttpClientUtil.doGet(host, path,map);
        return httpResponse;
    }



    /*public static List<GgSearchResult> dealCustomsearch(HttpResponse httpResponse, List<GgDomain> listDomain) throws IOException, ParseException {
        if(httpResponse.getStatusLine().getStatusCode()== HttpStatus.SC_OK){//成功
            String jsonStr = EntityUtils.toString(httpResponse.getEntity(), Consts.UTF_8);
            JSONObject resultObj = JSONObject.parseObject(jsonStr);
            JSONObject queries = resultObj.getJSONObject("queries");
            JSONArray request = queries.getJSONArray("request");
            JSONObject request0 = request.getJSONObject(0);
//            Integer count = request0.getInteger("count");
            Integer startIndex = request0.getInteger("startIndex");
            String searchTerms = request0.getString("searchTerms");//关键词

            JSONArray items = resultObj.getJSONArray("items");

            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String s = sdf.format(new Date());
            Date date =  sdf.parse(s);

            List<GgSearchResult> list = new ArrayList<>();
            for(int i=0; i<items.size(); i++)
            {
                JSONObject jsonObject = items.getJSONObject(i);
                String displayLink = jsonObject.getString("displayLink");

                //谷歌查询返回结果：
                GgSearchResult result = new GgSearchResult();
                for(GgDomain domain:listDomain)
                {
                    if(domain.getDomain().contains(displayLink))//当前搜索的结果中域名和我们自己的域名集合匹配
                    {
                        System.out.println(domain.getDomain()+"===匹配==="+displayLink+"===排名==="+(startIndex.longValue()+i));
                        result.setKeyWord(searchTerms);
                        result.setDomain(domain.getDomain());
                        result.setRanking(startIndex.longValue()+i);
                        result.setSearchDay(date);
                        list.add(result);
                    }
                }
            }
            return list;
        }
        return null;
    }*/

/*
    public static List<GgSearchResult> doSearch(List<GgKeyWords> listKeyWords, List<GgDomain> listDomain) throws IOException, ParseException, InterruptedException {
        if(listKeyWords!=null && listKeyWords.size()>0)
        {
            List<GgSearchResult> allResult = new ArrayList<>();
            Map<String, Object> allMap = new HashMap();

            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String s = sdf.format(new Date());
            Date date =  sdf.parse(s);

            boolean errorFlag = false;
            for(int i=0; i<listKeyWords.size(); i++) {
                GgKeyWords keyWord = listKeyWords.get(i);
                System.out.println("开始搜索关键字======>"+keyWord.getKeyWord());

                for(int j=0; j<10; j++) //循环10次，每次查10条记录，共查100条记录
                {
                    Thread.sleep(5000);//暂停5秒
                    System.out.println("===第"+(j+1)+"页===");
                    HttpResponse response = customsearch(keyWord.getKeyWord(), j * 10 + 1, 10);
                    System.out.println("response.getStatusLine().getStatusCode()==="+response.getStatusLine().getStatusCode());
                    if(response.getStatusLine().getStatusCode()== HttpStatus.SC_OK) {//成功
                        String jsonStr = EntityUtils.toString(response.getEntity(), Consts.UTF_8);
                        JSONObject resultObj = JSONObject.parseObject(jsonStr);
                        JSONArray items = resultObj.getJSONArray("items");
                        //System.out.println("items==>"+items);
                        if(items==null)
                        {
                            //System.out.println("item is null");
                            break;
                        }else{
                            //System.out.println("item is not null!!");
                        }

                        JSONObject queries = resultObj.getJSONObject("queries");
                        JSONArray request = queries.getJSONArray("request");
                        JSONObject request0 = request.getJSONObject(0);
                        //Integer count = request0.getInteger("count");
                        Integer startIndex = request0.getInteger("startIndex");
                        String searchTerms = request0.getString("searchTerms");//关键词

                        //List<GgSearchResult> list = new ArrayList<>();
                        for(int k=0; k<items.size(); k++)
                        {
                            JSONObject jsonObject = items.getJSONObject(k);
                            String displayLink = jsonObject.getString("displayLink");

                            for(GgDomain domain:listDomain)
                            {
                                if(domain.getDomain().contains(displayLink))//当前搜索的结果中域名和我们自己的域名集合匹配
                                {
                                    if(allMap.get(searchTerms+"<_>"+domain.getDomain())==null)
                                    {
                                        System.out.println(domain.getDomain()+"===匹配==="+displayLink+"===排名==="+(startIndex.longValue()+k));
                                        allMap.put(searchTerms+"<_>"+domain.getDomain(),startIndex.longValue()+k);
                                    }
                                }
                            }
                        }

                    }else if(response.getStatusLine().getStatusCode()== HttpStatus.SC_TOO_MANY_REQUESTS) {//请求过多
                        System.out.println("请求过多，超出数量限制！");
                        errorFlag = true;
                        break;
                    }else{
                        System.out.println("查询失败！");
                        errorFlag = true;
                        break;
                    }
                }
                if(errorFlag)//超出限制，以及中途查询失败，后面的关键字都放弃查询
                {
                    break;
                }

            }

            for (Map.Entry<String, Object> m : allMap.entrySet()) {
                String[] arr = m.getKey().split("<_>");
                GgSearchResult result = new GgSearchResult();
                result.setKeyWord(arr[0]);
                result.setDomain(arr[1]);
                result.setRanking((Long) m.getValue());
                result.setSearchDay(date);
                allResult.add(result);
                //System.out.println("key:" + m.getKey() + " value:" + m.getValue());
            }

            return allResult;
        }
        return null;
    }
*/

    public static List<GgSearchResult> doSearch(String keyWord, List<GgDomain> listDomain) throws IOException, ParseException, InterruptedException {
            List<GgSearchResult> searchResults = new ArrayList<>();
            Map<String, Object> allMap = new HashMap();

            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String s = sdf.format(new Date());
            Date date =  sdf.parse(s);

            boolean errorFlag = false;
                System.out.println("开始搜索关键字======>"+keyWord);

                for(int j=0; j<10; j++) //循环10次，每次查10条记录，共查100条记录
                {
                    Thread.sleep(5000);//暂停5秒
                    System.out.println("===第"+(j+1)+"页===");
                    HttpResponse response = customsearch(keyWord, j * 10 + 1, 10);
                    //System.out.println("response.getStatusLine().getStatusCode()==="+response.getStatusLine().getStatusCode());
                    if(response.getStatusLine().getStatusCode()== HttpStatus.SC_OK) {//成功
                        String jsonStr = EntityUtils.toString(response.getEntity(), Consts.UTF_8);
                        JSONObject resultObj = JSONObject.parseObject(jsonStr);
                        JSONArray items = resultObj.getJSONArray("items");
                        //System.out.println("items==>"+items);
                        if(items==null)
                        {
                            //System.out.println("item is null");
                            break;
                        }else{
                            //System.out.println("item is not null!!");
                        }

                        JSONObject queries = resultObj.getJSONObject("queries");
                        JSONArray request = queries.getJSONArray("request");
                        JSONObject request0 = request.getJSONObject(0);
                        //Integer count = request0.getInteger("count");
                        Integer startIndex = request0.getInteger("startIndex");
                        String searchTerms = request0.getString("searchTerms");//关键词

                        for(int k=0; k<items.size(); k++)
                        {
                            JSONObject jsonObject = items.getJSONObject(k);
                            String displayLink = jsonObject.getString("displayLink");

                            for(GgDomain domain:listDomain)
                            {
                                if(domain.getDomain().contains(displayLink))//当前搜索的结果中域名和我们自己的域名集合匹配
                                {
                                    if(allMap.get(searchTerms+"<_>"+domain.getDomain())==null)
                                    {
                                        System.out.println(domain.getDomain()+"===匹配==="+displayLink+"===排名==="+(startIndex.longValue()+k));
                                        allMap.put(searchTerms+"<_>"+domain.getDomain(),startIndex.longValue()+k);
                                    }
                                }
                            }
                        }

                    }else if(response.getStatusLine().getStatusCode()== HttpStatus.SC_TOO_MANY_REQUESTS) {//请求过多
                        System.out.println("请求过多，超出数量限制！");
                        errorFlag = true;
                        break;
                    }else{
                        System.out.println("查询失败！");
                        errorFlag = true;
                        break;
                    }
                }
                if(errorFlag)//超出限制，以及中途查询失败，后面的关键字都放弃查询
                {
                    //throw new RuntimeException("中途查询出错！");
                }



            for (Map.Entry<String, Object> m : allMap.entrySet()) {
                String[] arr = m.getKey().split("<_>");
                GgSearchResult result = new GgSearchResult();
                result.setKeyWord(arr[0]);
                result.setDomain(arr[1]);
                result.setRanking((Long) m.getValue());
                result.setSearchDay(date);
                searchResults.add(result);
                //System.out.println("key:" + m.getKey() + " value:" + m.getValue());
            }

            return searchResults;

    }

}
